<script>
import { defineComponent, watch, computed, reactive } from 'vue'
import { createNamespace } from '../utils'
import FanPicker from '../picker/picker.vue'

export default defineComponent({
	name: createNamespace('TimePicker')[0],
	options: { virtualHost: true },
	emits: ['update:show', 'update:modelValue', 'confirm', 'cancel'],
	components: { FanPicker },
	props: {
		modelValue: {
			type: Array,
			default: () => [],
		},
		show: {
			type: Boolean,
			default: false
		},
		title: String,
		filter: {
			type: [Function, null],
			default: null
		},
		cancelText: {
			type: String,
			default: '取消',
		},
		confirmText: {
			type: String,
			default: '确认',
		},
		second: {
			type: Boolean,
			default: false
		}
	},
	setup(props, { emit }) {
		const formatTime = (val, type) => {
			let arr = Array.from({ length: val }, (_, index) => index < 10 ? `0${index}` : index)
			if (props.filter) arr = props.filter(type, arr)
			arr = arr.map((item, index) => ({ text: item, id: index < 10 ? `0${index}` : String(index), index }))
			return arr
		}

		const state = reactive({
			innerShow: props.show,
			value: props.modelValue,
			hours: formatTime(24, 'hours'),
			minute: formatTime(60, 'minute'),
			second: formatTime(60, 'second'),
		})

		const list = computed(() => {
			let l = [state.hours, state.minute]
			if (props.second) l.push(state.second)
			return l
		})

		const onConfirm = (val) => emit('confirm', val)
		const onCancel = (val) => emit('cancel')

		watch(props.modelValue, (val) => {
			state.value = [...val]
		}, { deep: true })
		watch(() => state.value, (val) => {
			emit('update:modelValue', val)
		}, { deep: true })

		watch(() => props.show, (val) => state.innerShow = val)
		watch(() => state.innerShow, (val) => emit('update:show', val))

		return { state, list, onConfirm, onCancel }
	}
})
</script>

<template>
	<FanPicker v-model="state.value" v-model:show="state.innerShow" :data="list" value-key="id" :title="title"
		:cancel-text="cancelText" :confirm-text="confirmText" @confirm="onConfirm" @cancel="onCancel">
		<template v-if="$slots.default" #header>
			<slot />
		</template>
	</FanPicker>
</template>
